<script setup lang="ts">
const mask = ref(false);
const recorderManager = uni.getRecorderManager();
const startX = ref(0);
const startY = ref(0);
const length = ref(0);
let timer: number;
const needCancel = ref(false);
const emit = defineEmits(["success"]);
const visible = ref(true);

/**
 * 开始
 * @param e
 */
const handleTouchStart = (e: TouchEvent) => {
  mask.value = true;
  console.log("开始录制");

  recorderManager.start({
    duration: 10000,
  });

  startX.value = e.touches[0].pageX;
  startY.value = e.touches[0].pageY;
  timer = setInterval(() => {
    length.value += 1;
    if (length.value >= 60) {
      clearInterval(timer);
      handleTouchEnd();
    }
  }, 1000);
};

const handleTouchMove = (e: TouchEvent) => {
  if (
    startX.value - e.touches[0].pageX > 14 &&
    startY.value - e.touches[0].pageY > 50
  ) {
    needCancel.value = true;
  } else {
    needCancel.value = false;
  }
};
// 语音录制结束
const handleTouchEnd = () => {
  mask.value = false;
  clearInterval(timer);
  console.log("结束录制");
  recorderManager.stop();
  recorderManager.onStop((res) => {
    console.log(res);
    if (res.duration > 1000) {
      const message = {
        voice: res.tempFilePath,
        duration: res.duration,
        msgType: 2,
      };
    emit("success", message);
    }
    //	needCancel = false
  });
};
</script>

<template>
  <div class="sd">
    <div class="voice-tip" v-if="mask">
      <div>
        <span class="voice-tip-item" v-for="item in 10"></span>
      </div>
    </div>
    <div
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      class="msg-voice"
    >
      {{ mask ? "松开结束" : "按住说话" }}
    </div>
  </div>
</template>

<style lang="scss" scoped>
.msg-voice {
}
@mixin getItem($size) {
 @for $i from 1 through $size{
   .voice-tip-item:nth-child(#{$i}){
    animation-delay:unquote( $i/2 * -1+'s');
   }
 }
}
@keyframes toh{
  0%{
    height: 10px;
  }
  10%{
    height: 15px;
  }
 20%{
    height: 10px;
  }
  100%{
    height: 10px;
  }
}

.voice-tip {
  $size: 100px;
  position: fixed;
  left: 50%;
  width: $size;
  height: $size;
  top: 50%;
  left: 50%;
  margin-top: calc($size / 2 * -1);
  margin-left: calc($size / 2 * -1);
  background-color: rgba($color: #000, $alpha: 0.5);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  &-body{
    display: flex;
    align-items: center;
    justify-content: center;
  }
  &-item{
    width: 3px;
    height: 10px;
    background-color: #fff;
    display: inline-block;
    margin:5px 2px;
    animation: toh 10s both infinite;
    transition: all .5s;
  }
  @include getItem(10)
}
</style>
